/*
 * @Author: DaTree
 * @Date: 2021-09-04 10:21:11
 * @LastEditTime: 2021-09-07 09:11:09
 * @LastEditors: DaTree
 * @Description: DaTreeEdit
 * @FilePath: \demo_services\serverXHRSignalingChannel.js
 * 天将降大任于是人也，必先苦其心志，劳其筋骨，饿其体肤，空乏其身，行拂乱其所为。 ——《孟子•告子下》
 * Copyright 2021 DaTree
 */
var log = require('./log').log;
var connections = {}
var partner = {}
var messageFor = {}

// 排队发送JSON响应
function webrtcResponse (response, res) {
  log("replying with webrtc response " + JSON.stringify(response))
  res.writeHead(200, { "Content-Type": "application/json" })
  res.write(JSON.stringify(response))
  res.end()
}

//发送错误做为JSON WebRTC 响应
function webrtcError (err, res) {
  log("replying with webrtc error: " + err);
  webrtcResponse({ err }, res);
}

// 处理 ajax 请求以使用给定密钥进行连接
function connect (info) {
  var res = info.res;
  var query = info.query;
  var thisconnection;
  var newID = function () {
    return Math.floor(Math.random() * 100000000);
  }
  var connectFirstParty = function () {
    if (thisconnection.status == 'connected') {
      //删除配对和任何存储的消息
      delete partner[thisconnection.ids[0]];
      delete partner[thisconnection.ids[1]];
      delete messageFor[thisconnection.ids[0]];
      delete messageFor[thisconnection.ids[1]];
    }
    connections[query.key] = {};
    thisconnection = connections[query.key];
    thisconnection.status = "waiting";
    thisconnection.ids = [newID()];
    webrtcResponse({
      id: thisconnection.ids[0],
      status: thisconnection.status
    }, res);
  }
  var connectSecondParty = function () {
    thisconnection.ids[1] = newID();
    partner[thisconnection.ids[0]] = thisconnection.ids[1];
    partner[thisconnection.ids[1]] = thisconnection.ids[0];
    messageFor[thisconnection.ids[0]] = [];
    messageFor[thisconnection.ids[1]] = [];
    thisconnection.status = "connected";
    webrtcResponse({
      id: thisconnection.ids[1],
      status: thisconnection.status
    }, res);
  }
  log("Request handle 'connect' was called.");
  if (query && query.key) {
    thisconnection = connections[query.key] || { status: "new" };
    if (thisconnection.status == "waiting") {
      //前半部分就绪
      connectSecondParty();
      return;
    } else {
      //必须为新连接或 "connected" 状态
      connectFirstParty();
      return;
    }
  } else {
    webrtcError("必须提供 参数 query.key", res);
  }
}
exports.connect = connect;

function sendMessage (info) {
  log("postData received is ***" + info.postData + "***");
  var postData = JSON.parse(info.postData)
  var res = info.res;
  if (typeof postData === 'undefined') {
    webrtcError("反序列化json失败", res)
    return
  }
  if (typeof postData.message === 'undefined') {
    webrtcError("缺少 message 参数!", res)
    return
  }
  if (typeof postData.id === 'undefined') {
    webrtcError("缺少 id 参数", res)
    return
  }
  if (typeof partner[postData.id] === 'undefined') {
    webrtcError("无效的id" + postData.id, res);
    return;
  }
  messageFor[partner[postData.id]].push(postData.message)
  log("保存消息 *** " + postData.message + ' *** 目标id ' + partner[postData.id])
  webrtcResponse("保存消息 *** " + postData.message + ' *** 目标id ' + partner[postData.id], res);
}
exports.send = sendMessage;

//返回所有排队获取 info.postData.id 的消息
function getMesages (info) {
  var postData = JSON.parse(info.postData)
  var res = info.res;
  if (typeof postData === 'undefined') {
    webrtcError("反序列化json失败", res)
    return
  }
  if (typeof postData.id === 'undefined') {
    webrtcError("缺少 id 参数", res)
    return
  }
  if (typeof messageFor[postData.id] === 'undefined') {
    webrtcError("无效的id" + postData.id, res);
    return;
  }
  log("发送消息 *** " + JSON.stringify(messageFor[postData.id]) + ' *** 目标id' + postData.id)
  webrtcResponse({ 'msgs': messageFor[postData.id] }, res)
  messageFor[postData.id] = [];
}
exports.get = getMesages;